package com.yu.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yu.constant.JwtClaimsConstant;
import com.yu.model.Result;
import com.yu.model.dto.AdminDTO;
import com.yu.model.entity.Admin;
import com.yu.properties.JwtProperties;
import com.yu.service.AdminService;
import com.yu.mapper.AdminMapper;
import com.yu.utils.JwtUtil;
import com.yu.utils.StatusHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
* @author 33522
* @description 针对表【admin】的数据库操作Service实现
* @createDate 2023-12-18 12:03:04
*/
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
    implements AdminService{


    @Resource
    private JwtProperties jwtProperties;
    @Override
    public Result<String> login(AdminDTO adminDTO) {
        Admin phone = getOne(query().eq("phone", adminDTO.getPhone()));
        if(phone == null){
            return Result.error("账户不存在");
        }
        String password = DigestUtils.md5DigestAsHex(adminDTO.getPassword().getBytes());
        if(!password.equals(phone.getPassword())){
            return Result.error("账号或密码错误");
        }
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.ADMIN_ID, phone.getId());
        claims.put("status","admin");
        String jwt = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        StatusHolder.saveStatus("admin");
        return Result.success(jwt);
    }
}




